package com.mysoftbase.base.realm;

import com.mysoft.common.entity.User;
import com.mysoft.common.utils.JWTUtil;
import com.mysoft.service.service.UserRoleService;
import com.mysoft.service.service.UserService;
import com.mysoftbase.base.token.JWTToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author: JohnCoding
 * @Description: 自定义一个授权
 * @date: 2019/12/23 9:50
 */
@Slf4j
@Component
public class BaseRealm extends AuthorizingRealm {
    /**
     * 数据库存储的用户密码的加密salt，正式环境不能放在源代码里
     */
    private static final String encryptSalt = "F12839WhsnnEV$#23b";

    @Autowired
    UserService userService;

    @Autowired
    UserRoleService userRoleService;

    @Override
    public boolean isPermitted(PrincipalCollection principals, String permission) {
        System.out.println("这里处理鉴权");
        //返回true表示通过鉴权
        return super.isPermitted(principals, permission);
    }

    /**
     * 设置数据库密码散列加密,使用shiro的散列
     *
     * @param userService
     */
    public BaseRealm(UserService userService) {
        this.userService = userService;
//        this.setCredentialsMatcher(new HashedCredentialsMatcher(Sha256Hash.ALGORITHM_NAME));
    }


    /**
     * 权限验证
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //在这里处理权限
        String username = JWTUtil.getUsername(principals.toString());
        User user = userService.getByUserName(username);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        return simpleAuthorizationInfo;
    }

    /**
     * 登录认证
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     *
     * @param auth
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();
        // 解密获得username，用于和数据库进行对比
        String username = null;
        try {
            //这里工具类没有处理空指针等异常这里处理一下(这里处理科学一些)
            username = JWTUtil.getUsername(token);
        } catch (Exception e) {
            throw new AuthenticationException("heard的token拼写错误或者值为空");
        }
        if (username == null) {
            log.error("token无效(空''或者null都不行!)");
            throw new AuthenticationException("token无效");
        }
        User userBean = userService.getByUserName(username);
        if (userBean == null) {
            log.error("用户不存在!)");
            throw new AuthenticationException("用户不存在!");
        }
        if (!JWTUtil.verify(token, username, userBean.getPassword())) {
            log.error("用户名或密码错误(token无效或者与登录者不匹配)!)");
            throw new AuthenticationException("用户名或密码错误(token无效或者与登录者不匹配)!");
        }
        //获取盐
        ByteSource salt = ByteSource.Util.bytes(username);
        return new SimpleAuthenticationInfo(token, token, "BaseRealm");
    }

    /**
     * 必须重写此方法，不然Shiro会报错
     *
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }
}
